package dao

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"gorm.io/gorm"
)

// model接口
type IModel interface {

	// 返回model
	GetModel() interface{}

	// 返回表名
	GetTableName() string

	// 返回主键名称
	GetIdColumn() string

	// 返回联合主键名称
	GetUnionIdColumn() string
}

// dao基类
type BaseDao struct {
	Model IModel
}

// 通过主键获取
func (d *BaseDao) GetById(ctx context.Context, Db *gorm.DB, id interface{}, dest interface{}) error {
	return Db.Model(d.Model.GetModel()).
		Where(d.Model.GetIdColumn()+"=?", id).
		Take(dest).
		Error
}

// 通过联合主键获取
func (d *BaseDao) GetByUnionId(ctx context.Context, Db *gorm.DB, unionId interface{}, dest interface{}) error {
	return Db.Model(d.Model.GetModel()).
		Where(d.Model.GetUnionIdColumn()+"=?", unionId).
		Take(dest).
		Error
}

// 插入记录
func (d *BaseDao) Insert(ctx context.Context, Db *gorm.DB, record interface{}) error {
	return Db.Model(d.Model.GetModel()).
		Create(record).
		Error
}

// 根据id更新记录
func (d *BaseDao) UpdateById(ctx context.Context, Db *gorm.DB, id interface{}, updateParam map[string]interface{}) error {
	return Db.Model(d.Model.GetModel()).
		Where(d.Model.GetIdColumn()+"=?", id).
		Updates(updateParam).Error
}

// 根据联合主键id更新记录
func (d *BaseDao) UpdateByUnionId(ctx context.Context, Db *gorm.DB, unionId interface{}, updateParam map[string]interface{}) error {
	return Db.Model(d.Model.GetModel()).
		Where(d.Model.GetUnionIdColumn()+"=?", unionId).
		Updates(updateParam).Error
}

// 根据id删除记录
func (d *BaseDao) RemoveById(ctx context.Context, Db *gorm.DB, id interface{}) error {
	return Db.Where(d.Model.GetIdColumn()+"=?", id).
		Delete(d.Model.GetModel()).Error
}

// 根据联合抓紧id删除记录
func (d *BaseDao) RemoveByUnionId(ctx context.Context, Db *gorm.DB, unionId interface{}) error {
	return Db.Where(d.Model.GetUnionIdColumn()+"=?", unionId).
		Delete(d.Model.GetModel()).Error
}

// 分页查询
func (d *BaseDao) PageByParams(ctx context.Context, Db *gorm.DB, simpleWhere *gorms.SimpleWhere, pageParam *gorms.Param, dest interface{}) (*gorms.Paginator, error) {
	db := Db.Model(d.Model.GetModel())
	if simpleWhere != nil {
		db = simpleWhere.DoWhere(db)
	}
	paginator, err := gorms.Paging(db, pageParam, dest)
	return paginator, err
}

// 列表
func (d *BaseDao) ListByParams(ctx context.Context, Db *gorm.DB, simpleWhere *gorms.SimpleWhere, dest interface{}) error {
	db := Db.Model(d.Model.GetModel())
	if simpleWhere != nil {
		db = simpleWhere.DoWhere(db)
	}
	db.Find(dest)
	err := db.Error
	return err
}
